﻿using System;
using UnityEngine;

namespace TC
{
    public class ConnectSurface : ConnectionSurface<PortConnection>
    {
        public bool isActive = false;
        public PortSurface sourcePortSurf;
        public PortSurface targetPortSurf;

        public Vector2 sourcePos { get => sourcePortSurf.portRelativeRect.position + sourcePortSurf.portRelativeRect.size / 2; }
        public Vector2 targetPos { get => targetPortSurf.portRelativeRect.position + targetPortSurf.portRelativeRect.size / 2; }
        private Color color { get => targetPortSurf.portColor; }
        
        public ConnectSurface(PortConnection t, PortSurface portSurf_1, PortSurface portSurf_2) : base(t)
        { 
            if (portSurf_1.target.IsInput && !portSurf_2.target.IsInput)
            {
                sourcePortSurf = portSurf_2;
                targetPortSurf = portSurf_1;
            }
            if (!portSurf_1.target.IsInput && portSurf_2.target.IsInput)
            {
                sourcePortSurf = portSurf_1;
                targetPortSurf = portSurf_2;
            }
        }

        public override void OnDraw(Rect graphRect)
        {
            BezierUtil.DrawBezier(sourcePos, targetPos, color, isActive);
        }

        public override void CheckIsContaining()
        {
            Event e = Event.current;
            isContaining = BezierUtil.Contains(sourcePos, targetPos, isActive, e.mousePosition);
        }

        public PortSurface GetOther(PortSurface portSurface)
        {
            if (portSurface == sourcePortSurf) { return targetPortSurf; }
            if (portSurface == targetPortSurf) { return sourcePortSurf; }
            return null;
        }

        public override void OnCreate()
        {
            base.OnCreate();

            sourcePortSurf.OnConnect();
            targetPortSurf.OnConnect();
        }

        public override void OnDestroy()
        {
            base.OnDestroy();
            
            sourcePortSurf.OnDisconnect();
            targetPortSurf.OnDisconnect();
        }
    }
}